﻿using Devices;
using DevicesView.Entity;
using DevicesView.Logic.App;
using DevicesView.Model.ViewData;
using DevicesWPF.Logic;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;


namespace DevicesView
{
    /// <summary>
    /// UCTestResult.xaml 的交互逻辑
    /// </summary>
    public partial class UCTestResult : UserControl
    {

        //private List<Devices.Command> cmds;
        private ObservableCollection<ViewCMD> cmds;
        //private Logic.TestingsLogic logic = new Logic.TestingsLogic();
        private static Logic.Test.ResultLogic resultLogic = null;
        private Devices.IDevices idev;
        private Action<UCTestResult, Command> saveCommandIng;
        private Action<UCTestResult, Command> deleteCommanded;

        public event Action<UCTestResult, Command> SaveCommandIng
        {
            add
            {
                saveCommandIng += value;
            }
            remove
            {
                saveCommandIng -= value;
            }
        }
        public event Action<UCTestResult, Command> DeleteCommanded
        {
            add
            {
                deleteCommanded += value;
            }
            remove
            {
                deleteCommanded -= value;
            }
        }
        static UCTestResult()
        {
            resultLogic = new Logic.Test.ResultLogic();
        }
        public UCTestResult()
        {
            InitializeComponent();
            cmds = new ObservableCollection<ViewCMD>();
            DataGridCMDS.ItemsSource = cmds;


            DevicesView.Logic.Test.ResultLogic resultLogic = new DevicesView.Logic.Test.ResultLogic();

            if (DevicesCollection.Commands != null)
                DevicesCollection.Commands.ForEach(o=>cmds.Add(new ViewCMD(o)));

            if (resultLogic.Completed != null)
                resultLogic.Completed.ForEach(o => cmds.Add(new ViewCMD(o)));
        }

        public UCTestResult(IDevices device)
        {
            InitializeComponent();
            cmds = new ObservableCollection<ViewCMD>();
            DataGridCMDS.ItemsSource = cmds;
            idev = device;

            List<Command> copy = device.GetCommandes();
            if (copy != null)
            {
                foreach (var item in copy)
                    cmds.Add(new ViewCMD(item));
            }

            if (resultLogic.Completed != null && resultLogic.Completed.Count > 0)
            {
                foreach (var item in resultLogic.Completed)
                    if (item.CMD?.Info.Code == device.Info.Code)
                        cmds.Add(new ViewCMD(item));
            }
        }


        public void RefreshData()
        {
        }


        public void AddCmds(Command cmd)
        {
            int index = -1;
            for (int i = 0; i < cmds.Count; i++)
            {
                if (cmds[i].Result != null)
                {
                    index = i;
                    break;
                }
            }

            if (index >= 0)
                cmds.Insert(index, new ViewCMD(cmd));
            else
                cmds.Add(new ViewCMD(cmd));
        }
        public void RemoveCmds(Command cmd)
        {
            ViewCMD vc = cmds.FirstOrDefault(o => o.Command == cmd);
            if (vc != null)
            {
                cmds.Remove(vc);
                if (idev != null && cmd.Status == 128)
                    idev.RemoveCommand(cmd.Id);

                if (cmd.Result != null)
                    resultLogic.RemoveCompleted(cmd.Result);
            }
        }
        public void SetResult(Result result)
        {
            //if (idev == null || idev.CMDS == null || idev.CMDS.Count == 0)
            //{
            //    SetResultByCommand(result);
            //    return;
            //}

            //DevAutoConfigInfo info = DevicesLogic.GetDevicesTest(idev.Info.Code);
            //if (info == null || !info.Selected || info.Tests == null || info.Tests.Count == 0)
            //{
            //    SetResultByCommand(result);
            //    return;
            //}

            //for (int i = idev.CMDS.Count - 1; i >= 0; i--)
            //{
            //    if (idev.CMDS[i].Id == result.CMD.Id || idev.CMDS[i].Name == result.CMD.Name || idev.CMDS[i].PetName != result.CMD?.PetName)
            //        continue;
            //    DevicesTest test = info?.Tests?.FirstOrDefault(o => o.Name == result.CMD.Name);
            //    if (test == null || test.Items == null || test.Items.Count == 0)
            //        continue;

            //    Result newResult = new Result();
            //    newResult.CMD = idev.CMDS[i];
            //    newResult.Date = result.Date;
            //    newResult.Devices = result.Devices;
            //    newResult.Remarks = result.Remarks;
            //    newResult.ResultDatas = new List<ResultItem> { };
            //    newResult.Source = result.Source;
            //    newResult.Tag = result.Tag;
            //    newResult.Type = result.Type;
            //    foreach (var item in test.Items)
            //    {
            //        ResultItem ri = result?.ResultDatas?.FirstOrDefault(o => o.Code == item.Code);
            //        if (ri != null)
            //        {
            //            newResult.ResultDatas.Add(ri);
            //            result.ResultDatas.Remove(ri);
            //        }
            //    }
            //    SetResultByCommand(newResult);
            //    idev.RemoveCommand(idev.CMDS[i].Id);
            //}

            SetResultByCommand(result);
        }


        private void SetResultByCommand(Result result)
        {
            ViewCMD command = cmds.FirstOrDefault(o => o.Id == result.CMD.Id);
            if (command != null)
            {
                command.Result = result;
                command.StatusString = "✔";
                cmds.Remove(command);
                cmds.Add(command);
                DataGridCMDS.SelectedItem = command;
                SelectCommand();
                //resultLogic.AddCompleted(result);
            }
        }




        public bool SelectConnamd(Command cmd)
        {
            int index = -1;
            for (int i = 0; i < cmds.Count; i++)
            {
                if (cmds[i].Command == cmd)
                {
                    index = i;
                    break;
                }
            }
            if (index < 0)
                return false;
            DataGridCMDS.SelectedIndex = index;
            return true;
        }


        private void SelectCommand()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (this.DataGridCMDS.SelectedItem != null)
                {
                    ViewCMD cmd = DataGridCMDS.SelectedItem as ViewCMD;
                    DateTimePicker1.SelectedDate = cmd.Date;
                    TestItems.Result = cmd.Result;
                }
                else
                {
                    TestItems.Result = null;
                }
            }));
        }

        private void DataGridResult_Selected(object sender, RoutedEventArgs e)
        {
            SelectCommand();
        }

        private void DataGridResult_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            SelectCommand();
        }
        /// <summary>
        /// 保存结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (DataGridCMDS.SelectedItems == null || DataGridCMDS.SelectedItems.Count == 0)
                return;


            ViewCMD viewCMD = DataGridCMDS.SelectedItem as ViewCMD;
            Command cmd = viewCMD.Command;
            if (cmd == null || cmd.Result == null)
                return;
            if (comboBoxEditDoc.SelectedItem == null)
            {
                BCL.WPFComponent.UCMessageBox.Show("请选择操作医生!");
                return;
            }
            cmd.Result = TestItems.Result;
            cmd.Operator = (comboBoxEditDoc.SelectedItem as Doctor).Name;
            cmd.OperatorCode = (comboBoxEditDoc.SelectedItem as Doctor).Id.ToString();
            saveCommandIng?.Invoke(this, cmd);


        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (AppResource.CurrentResource.Doctors != null)
            {
                comboBoxEditDoc.ItemsSource = AppResource.CurrentResource.Doctors;
                comboBoxEditDoc.DisplayMemberPath = "Name";
                Doctor info = AppResource.CurrentResource.Doctors.FirstOrDefault(o => o.Name == AppResource.CurrentResource.LoginUser?.UserName);
                if (info != null)
                    comboBoxEditDoc.SelectedItem = info;
            }
        }



        private void DataGridCMDS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectCommand();
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (column1.Width.Value == 0)
                column1.Width = new GridLength(5, GridUnitType.Star);
            else
                column1.Width = new GridLength(0, GridUnitType.Star);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

            Command cmd = (DataGridCMDS.SelectedItem as ViewCMD).Command;
            if (cmd == null)
                return;
            deleteCommanded?.Invoke(this, cmd);
        }
    }

}
